from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey

class Comment(models.Model):
    '''
    包括评论和回复
    '''
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    text = models.TextField()
    comment_time = models.DateTimeField(auto_now_add=True)
    # 评论发送者
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comments')
    # 评论回复对象
    reply_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='replies', null=True)
    # 回复对应的最顶层评论
    root = models.ForeignKey('self', on_delete=models.CASCADE, related_name='replies', null=True)
    # 回复的评论
    parent = models.ForeignKey('self', on_delete=models.CASCADE, related_name='child_reply', null=True)

    def __str__(self):
        return '<{}>:{}'.format(self.pk, self.text[:15])

    class Meta:
        # 为了让回复是先回复的在前面，采用由早到晚排列
        ordering=['comment_time']
    
